package com.example.guiguiapplicatio.api;

import android.os.NetworkOnMainThreadException;
import android.util.Log;

import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class GetCountTotalApi  {
    private final Gson gson=new Gson();
    private AllCallback allCallback;
    public static String ip= "10.34.124.55";
    public void setAllCallback(AllCallback allCallback) {
        this.allCallback = allCallback;
    }
    public void performGetCountTotal(){
        new Thread(()->{
            String url="http://"+ip +":9090/counttotal";
            Headers headers = new Headers.Builder()
                    .add("Accept", "application/json, text/plain, */*")
                    .add("Content-Type", "application/json")
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    // 将请求头加至请求中
                    .headers(headers)
                    .get()
                    .build();
            try {
                OkHttpClient client = new OkHttpClient();
                //发起请求，传入callback进行回调
                client.newCall(request).enqueue(callback);
            }catch (NetworkOnMainThreadException ex){
                ex.printStackTrace();
            }
        }).start();
    }
    private final Callback callback=new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            //TODO 请求失败处理
            e.printStackTrace();
            if (allCallback != null) {
                allCallback.onFailure(e.getMessage());
            }
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            Type jsonType = new TypeToken<ResponseBody<Object>>(){}.getType();
            // 获取响应体的json串
            String body = response.body().string();
            Log.d("info", body);
            // 解析json串到自己封装的状态
            ResponseBody<Object> dataResponseBody = gson.fromJson(body,jsonType);
            Log.d("info", dataResponseBody.toString());
            if (allCallback != null) {
                try {
                    allCallback.onSuccess(dataResponseBody);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    };
}
